package com.pay.ioopos.fragment;

import android.os.Environment;

import com.pay.ioopos.DataFactory;
import com.pay.ioopos.DeviceUtils;
import com.pay.ioopos.HttpUtil;
import com.pay.ioopos.Utils;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Response;

import static com.pay.ioopos.fragment.TipFragment.TipType.WAIT;

public class UpdateFragment extends TipVerticalFragment {
    private OnUpdateListener listener;
    public UpdateFragment() {
        super(WAIT, "正在检查版本");
    }

    @Override
    public boolean useNetwork() {
        return true;
    }

    @Override
    public void execute() throws Exception {
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String sn = DeviceUtils.sn(getActivity());
        String key = DataFactory.getDataStore().getTransKey();
        String sign = Utils.sha256(sn + timestamp + key);
        JSONObject json = new JSONObject();
        json.put("version", "v2");
        json.put("deviceSn", sn);
        json.put("brand", "ioopos");
        json.put("deviceVersion", DeviceUtils.appVersion(getContext()));// DeviceUtils.appVersion(getContext())
        json.put("timestamp", timestamp);
        json.put("sign", sign);
        String jsonString = json.toString();
        jsonString = HttpUtil.post("https://app.campusplus.com/dzxyk-hd/device/update.php", jsonString);
        json = new JSONObject(jsonString);
        String needUpdate = json.getString("needUpate");
        if (needUpdate.equals("0")) {
            listener.onChecked(false);
            return;
        }
        listener.onChecked(true);

        String downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        String filePath = downloadDir + File.separator + "ioopos-pay.apk";

        File file = new File(filePath);
        if (!file.exists()) {
            file.createNewFile();
        }
        file.setWritable(true);
        byte[] bytes = new byte[1024];
        int length;
        Response res = HttpUtil.getResponse(json.getString("fileUrl"));
        final int totalLength = Integer.parseInt(res.header("content-length"));
        int loadedLength = 0;
        try (InputStream is = res.body().byteStream(); FileOutputStream os = new FileOutputStream(file)) {
            while ((length = is.read(bytes)) != -1) {
                os.write(bytes, 0, length);
                loadedLength += length;
                listener.onDownloading(totalLength, loadedLength);
            }
            os.flush();
        }
        listener.onDownload(filePath);
    }

    public interface OnUpdateListener {
        void onChecked(boolean toUpdate);
        void onDownloading(int totalLength, int loadedLength);
        void onDownload(String file);
        void onError(String msg);
    }

    public OnUpdateListener getListener() {
        return listener;
    }

    public void setListener(OnUpdateListener listener) {
        this.listener = listener;
    }

}
